import React, {useEffect, useState} from "react";
import { Layout, Card, Row, Col, Statistic, List, Image, Divider, Typography, Tag, Avatar } from 'antd';
import { StarTwoTone, RightCircleTwoTone, RightOutlined } from '@ant-design/icons';
import './ProductPage.css';
import {useParams} from "react-router-dom";
import {getProductList} from "../../services/product";
import ShowProductComponent from "./ShowProductComponent";

const { Content } = Layout;
const { Text } = Typography;



// 自定义星星组件
const Star = ({ filled }) => (
    <StarTwoTone twoToneColor={`${filled ? "#FB5B40" : ''}`} />
);

// 用于渲染单个评价
const ReviewItem = ({ avatar, name, comment, rating }) => {
    const stars = [];
    for (let i = 0; i < 5; i++) {
        stars.push(<Star key={i} filled={i < rating} />);
    }

    return (
        <div className="review-item">
            <div className="review-avatar-info">
                <Avatar src={avatar} alt={name} />
                <div className="review-meta">
                    <p className="review-name">{name}</p>
                    <div className="review-rating">{rating !== undefined ? stars : null}</div>
                </div>
            </div>
            <p className="review-comment">{comment}</p>
        </div>
    );
};



// 接入前端逻辑

const ProductInfoComponents = () => {
    const { id } = useParams();
    const [productList, setProductList] = useState([]);
    const [product, setProduct] = useState({});
    const [servicesList, setServicesList] = useState([]);

    useEffect(() => {
        fetchProductList();
    }, []);

    useEffect(() => {
        // const product =
        let foundProduct = productList.find(p => p.id === parseInt(id));
        if (foundProduct) {
            // 确保 product 和 services 存在后再进行操作
            setProduct(foundProduct);

            // 检查 foundProduct.services 是否存在，然后再使用 map 函数
            if (foundProduct.services) {
                const updatedServicesList = foundProduct.services.map((service, index) => (
                    <Tag key={index} color="green">
                        {service}
                    </Tag>
                ));
                setServicesList(updatedServicesList);
            }
        } else {
            // 如果没有找到产品，可以设置默认状态或者进行其他操作
            setProduct({ services: [] }); // 设置默认的空服务列表
            setServicesList([]); // 设置空的服务列表状态
        }
    }, [productList, id]);

    const fetchProductList = () => {
        getProductList({ page: 1, pageSize: 10 }).then(response => {
            if (response && response.result) {
                // console.log('Product List:', response.result);
                setProductList(response.result);
            } else {
                console.error('Error fetching product list: Invalid response');
            }
        }).catch(error => {
            console.error('Error fetching product list:', error);
        });
    };

    return (
        <>
            <div style={{ minHeight: '100vh', margin: 'auto', backgroundColor: '#fff' }}>
                <ShowProductComponent products={product}/>
                <Content style={{ padding: '15px' }}>
                    <Card bordered={false} >
                        <div className="product-name">{product.productName}</div>
                        <Text className="intro-name">{product.description}</Text>
                        <Row gutter={16} style={{ marginTop: '20px' }}>
                            <Col span={24} >
                                <Statistic value={'￥'+product.price} className="price-statistic" />
                            </Col>
                        </Row>
                        <Row gutter={16} style={{ marginTop: '20px'}}>
                            <Col span={8} style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                                <Statistic title="销量" value={product.sales} className="small-statistic" />
                            </Col>
                            <Col span={8} style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                                <Statistic title="库存" value={product.stock} className="small-statistic" />
                            </Col>
                            <Col span={8} style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                                <Statistic title="浏览量" value={product.views} className="small-statistic" />
                            </Col>
                        </Row>
                        <List
                            className="bordered-list"
                            dataSource={product.parameters}
                            renderItem={item => (
                                <List.Item style={{ display: 'flex', alignItems: 'center' }}>
                                    <span style={{fontSize: '17px', flex: 1 }}>{item}</span>
                                    <RightCircleTwoTone twoToneColor="#FB5B40" style={{fontSize: '20px',marginLeft: '10px',}}/>
                                </List.Item>
                            )}
                            style={{ marginTop: '20px' }}
                        />
                        <Divider />
                        <Text><b>服务：</b>{servicesList}</Text>
                    </Card>

                    <Card bordered={false} style={{ marginTop: '20px' }}>
                        <div className="intro-container">
                            <Text className="intro-product">商品评价</Text>
                            <div className="review-title">
                                <p>平均评分  {product.reviews}</p>
                                <StarTwoTone twoToneColor="#FB5B40"/>
                                <RightOutlined />
                            </div>
                        </div>
                        <Divider />
                        <div className="review-list">
                            { product && product.userReviews && product.userReviews.map((review, index) => (
                                <ReviewItem
                                    key={index} // 使用索引作为key，但在真实场景中，建议使用唯一标识符
                                    avatar={review.avatar}
                                    name={review.name}
                                    comment={review.comment}
                                    rating={review.rating}
                                />
                            ))}
                        </div>
                    </Card>

                    <Card title="商品详情" bordered={false} style={{ marginTop: '20px' }}>
                        <Row >
                            {product && product.details&&product.details.map((src, index) => (
                                <Col key={index}>
                                    <Image src={src} />
                                </Col>
                            ))}
                        </Row>
                    </Card>
                </Content>
                <div style={{ height:'90px'}}></div>
            </div>
        </>
    );
};
export default ProductInfoComponents;
